/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.admin;

import cn.easyplatform.EasyPlatformWithLabelKeyException;
import cn.easyplatform.entities.EntityInfo;
import cn.easyplatform.entities.beans.ResourceBean;
import cn.easyplatform.entities.transform.TransformerFactory;
import cn.easyplatform.i18n.I18N;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.messages.request.admin.ServiceRequestMessage;
import cn.easyplatform.messages.response.SimpleResponseMessage;
import cn.easyplatform.messages.vos.admin.ServiceVo;
import cn.easyplatform.services.AbstractService;
import cn.easyplatform.services.IDataSource;
import cn.easyplatform.services.system.DataSourceService;
import cn.easyplatform.spi.extension.ApplicationService;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.type.ServiceType;
import cn.easyplatform.type.StateType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class SetServiceStateCmd extends AbstractCommand<ServiceRequestMessage> {

    private static final Logger log = LoggerFactory.getLogger(SetServiceStateCmd.class);

    /**
     * @param req
     */
    public SetServiceStateCmd(ServiceRequestMessage req) {
        super(req);
    }

    @Override
    public IResponseMessage<?> execute(CommandContext cc) {
        ServiceVo vo = req.getBody();
        if (vo.getType() == ServiceType.PROJECT) {
            cc.getProjectService().setState(vo.getState());
        } else if (vo.getType() == ServiceType.DATASOURCE) {
            if (cc.getProjectService() == null) {
                IDataSource dataSource = (IDataSource) cc.getEngineConfiguration().getService(vo.getId());
                if (vo.getState() == StateType.STOP)
                    dataSource.stop();
                else if (vo.getState() == StateType.RESET) {
                    dataSource.resetDataSourceStat();
                    return new SimpleResponseMessage(dataSource.getRuntimeInfo());
                } else {
                    EntityInfo entity = cc.getEntityDao().getModel(vo.getId());
                    ResourceBean rb = TransformerFactory.newInstance()
                            .transformFromXml(entity);
                    AbstractService s = new DataSourceService(cc.getProjectService(), rb);
                    s.setEngineConfiguration(cc.getEngineConfiguration());
                    s.start();
                    dataSource.start();
                    return new SimpleResponseMessage(dataSource.getRuntimeInfo());
                }
            } else {
                if (vo.getState() == StateType.STOP)
                    cc.getProjectService().getService(vo.getId()).stop();
                else if (vo.getState() == StateType.RESUME) {
                    ApplicationService s = cc.getProjectService().getService(vo.getId());
                    s.stop();
                    s.start();
                    return new SimpleResponseMessage(s.getStartTime());
                } else if (vo.getState() == StateType.RESET) {
                    IDataSource s = (IDataSource) cc.getProjectService().getService(vo.getId());
                    s.resetDataSourceStat();
                    return new SimpleResponseMessage(s.getRuntimeInfo());
                } else {
                    EntityInfo entity = cc.getEntityDao().getModel(vo.getId());
                    ResourceBean rb = TransformerFactory.newInstance()
                            .transformFromXml(entity);
                    AbstractService s = new DataSourceService(cc.getProjectService(), rb);
                    s.setEngineConfiguration(cc.getEngineConfiguration());
                    s.start();
                    return new SimpleResponseMessage(s.getStartTime());
                }
            }
        } else if (vo.getType() == ServiceType.JOB) {
            if (vo.getId() == null) {//动态任务
                if (vo.getState() == StateType.START) {
                    cc.getProjectService().getCustomJob().start();
                    return new SimpleResponseMessage(cc.getProjectService().getCustomJob().getJobs());
                } else if (vo.getState() == StateType.STOP) {
                    if (vo.getValue("id") != null)
                        cc.getProjectService().getCustomJob().stop(Long.parseLong(vo.getAsString("id")));
                    else
                        cc.getProjectService().getCustomJob().stop();
                } else if (vo.getState() == StateType.RESET) {
                    long id = Long.parseLong(vo.getAsString("id"));
                    Date time = vo.getAsDate("time");
                    return new SimpleResponseMessage(cc.getProjectService().getCustomJob().modify(id, time));
                } else
                    return new SimpleResponseMessage(cc.getProjectService().getCustomJob().getJobs());
            } else {
                if (vo.getState() == StateType.STOP)// 停止
                    cc.getProjectService().getScheduleHandler().stop(vo.getId());
                else if (vo.getState() == StateType.START) {// 启动
                    ResourceBean rb = cc.getEntity(vo.getId());
                    return new SimpleResponseMessage(cc.getProjectService().getScheduleHandler().start(rb));
                } else if (vo.getState() == StateType.PAUSE) {// 暂停
                    return new SimpleResponseMessage(cc.getProjectService().getScheduleHandler().pause(vo.getId()));
                } else if (vo.getState() == StateType.RESUME) {// 继续
                    return new SimpleResponseMessage(cc.getProjectService().getScheduleHandler().resume(vo.getId()));
                }
            }
        } else if (vo.getType() == ServiceType.USER) {
            cc.getProjectService().getSessionManager()
                    .setState(vo.getId(), vo.getState());
        } else if (vo.getType() == ServiceType.CUSTOM_SERVICE) {
            if (vo.getState() == StateType.STOP) {
                ApplicationService as = cc.getProjectService().getService(vo.getId());
                if (as != null) {
                    as.stop();
                    cc.getProjectService().removeService(vo.getId());
                }
            } else {
                try {
                    ApplicationService as = cc.getProjectService().startService(vo.getId());
                    return new SimpleResponseMessage(as.getRuntimeInfo());
                } catch (Exception e) {
                    if (e instanceof EasyPlatformWithLabelKeyException)
                        return new SimpleResponseMessage("e050", I18N.getLabel(e.getMessage(), ((EasyPlatformWithLabelKeyException) e).getArgs()));
                    else {
                        if (log.isErrorEnabled())
                            log.error("start service " + vo.getId(), e);
                        return new SimpleResponseMessage("e051", e.getMessage());
                    }
                }
            }
        }
        return new SimpleResponseMessage();
    }

}
